/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dahg.project.istu.web.tree;

import com.dahg.project.istu.controller.bean.menu.IMenuService;
import com.dahg.project.istu.controller.model.Menu;
import com.dahg.project.istu.controller.model.Rol;
import java.util.List;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;

/**
 *
 * @author dahg
 */
public class TreeMenuFactory {
    
    private Rol rol;
    private IMenuService service;
    private Boolean todos;
    
    public TreeNode getModel(Rol rol, IMenuService service, Boolean todos) {
        TreeNode model = new DefaultTreeNode("root");
        
        this.todos = todos;
        List<Menu> rootMenu = (todos)?
                service.getAllMenu():
                service.getRootMenu(rol);
        
        if(rootMenu==null || rootMenu.isEmpty()) return model;
        
        this.rol = rol;
        this.service = service;        
        
        for(Menu menu: rootMenu) {
            if(isSubMenu(menu)) {
                TreeNodeMenu subMenu = new TreeNodeMenu(menu, NodeType.SUB_MENU, model);
                addItemsToSubMenu(subMenu);
            }
            else
                new TreeNodeMenu(menu, NodeType.ITEM, model);
        }
        
        return model;
    }
    
    private void addItemsToSubMenu(TreeNodeMenu subMenuNode) {        
        List<Menu> childs = (todos)?
                service.getMenuChilds(subMenuNode.getMenu()):
                service.getMenuChilds(subMenuNode.getMenu(), rol);
        
        if(!childs.isEmpty()) {
            for(Menu child:childs) {
                if(isSubMenu(child)) {
                    TreeNodeMenu subMenuChild = new TreeNodeMenu(child, NodeType.SUB_MENU, subMenuNode);
                    addItemsToSubMenu(subMenuChild);
                }
                else
                    new TreeNodeMenu(child, NodeType.ITEM, subMenuNode);
            }
        }
    }
    
    public boolean isSubMenu(Menu menu) {
        return (menu.getTarget()==null || menu.getTarget().isEmpty());
    }
}
